package interpreter.debugger.ui;

import interpreter.debugger.DebugVirtualMachine;

/**
 * Sets breakpoint in code
 *
 * @author Kris Selbekk
 */
public class SetBrkPtCommand extends Command {
    private boolean wrongSyntax, illegalPlacement;


    public void init(DebugVirtualMachine dvm) {
        super.init( dvm );
        wrongSyntax = false;
        illegalPlacement = false;
    }

    /**
     * Sets the break point line
     *
     * @param args the command and arguments
     */
    public void exec( String[] args ) {
        int line;

        // If a break point number is not given, return.
        if( args.length < 2 ) {
            wrongSyntax = true;
            return;
        }

        // Runs through all arguments and sets break points at all of them
        for( int i = 1; i < args.length; i++ ) {
            
            try {
                line = Integer.parseInt( args[i] );
            } catch( NumberFormatException nfe ) {
                wrongSyntax = true;
                return;
            }

            // Checks for negative numbers
            if( line <= 0 || line > dvm.getSourceNumLines() ) {
                wrongSyntax = true;
                return;
            }

            // Checks for illegal placement
            // Breakpoints can only be set on the beginning of
            //     blocks, decl, if, while, return, assign
            String lineSrc = dvm.getSource(line).trim();
            if( lineSrc.startsWith("}") || 
                lineSrc.startsWith("else") ||
                lineSrc.length() == 0 ) {
                wrongSyntax = true; return;
            }

            // Sets breakpoint
            dvm.setBreakpoint(line); // NO BOUNDS checking
        }
    }
    public void print() {
        StringBuilder out = new StringBuilder();
        if( wrongSyntax ) {
            out.append("Wrong syntax. \n Correct syntax is: \"setb <line#> [<line#2> (...) <line#n>]\"\n");
            out.append(" Line # must be within bounds and on a line starting with either\n");
            out.append("  blocks, decl, if, while, return, assign");
        }
        else out.append("Breakpoint(s) set.");

        System.out.println(out); 
        wrongSyntax = false; // resets
    }
}
